package net.dataforte.tooonebee;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class provides a method for finding and instantiating SPIs according to the JAR Service Provider specification 
 * 
 * @author tst
 *
 */
public class ServiceFinder {
	private static Logger log = LoggerFactory.getLogger(ServiceFinder.class);
	private static final Pattern nonCommentPattern = Pattern.compile( "^([^#]+)" );
	
	/**
	 * Scans the classpath for Service Provider files for the specified class. Returns a list of SPI instances
	 * 
	 * @param <T>
	 * @param clazz
	 * @return
	 */
	public static <T> List<? extends T> findServices(Class<T> clazz) {
		List<T> spis = new ArrayList<T>();
		
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		Enumeration<?> resources;
		
		try {
			resources = classLoader.getResources("META-INF/services/"+clazz.getName());
		} catch (IOException e) {
			log.error("Could not load service files for interface "+clazz.getName(), e);
			return spis;
		}
		
		while(resources.hasMoreElements()) {
			URL url = (URL)resources.nextElement();
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
				String line;
				while( (line = reader.readLine())!=null) {
					line = line.trim();
					Matcher m = nonCommentPattern.matcher( line );
					if ( m.find() ) {
						String spiClassName = m.group().trim();
						try {
							Class<?> spiClass = Class.forName(spiClassName, true, classLoader);
							T spi = spiClass.asSubclass(clazz).newInstance();
							spis.add(spi);
						} catch (NoClassDefFoundError ncdfe) {
							log.info("Could not instantiate SPI class "+spiClassName+" because of missing dependency "+ncdfe.getMessage());
						} catch (ClassCastException cce) {
							log.warn("Skipping SPI class "+spiClassName+" as it does not implement interface "+clazz.getName());	
						} catch (ClassNotFoundException cnfe) {
							log.warn("Could not find SPI class "+spiClassName);
						} catch (InstantiationException e) {
							log.warn("Could not instantiate SPI class "+spiClassName);
						} catch (IllegalAccessException e) {
							log.warn("Could not instantiate SPI class "+spiClassName);
						}
					}
				}
				reader.close();
			} catch (IOException ioe) {
				log.warn("Error while reading SPIs from "+url.toString(), ioe);
			}
		}
		return spis;
	}
}
